package com.oa.pm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.joneying.common.annotation.CommonService;
import com.joneying.common.web.response.Resp;
import com.oa.core.PageResult;
import com.oa.core.constant.Constant;
import com.oa.core.exception.BusinessException;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.pm.dto.CompanyDTO;
import com.oa.pm.dto.OrganizationDTO;
import com.oa.pm.dto.OrganizationUpdateDTO;
import com.oa.pm.entity.Organization;
import com.oa.pm.mapper.OrganizationMapper;
import com.oa.pm.service.IOrganizationService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.oa.pm.vo.OrganizationDetailsVO;
import com.oa.pm.vo.OrganizationTreeVO;
import com.oa.pm.vo.OrganizationVo;
import com.oa.system.entity.User;
import com.oa.system.mapper.UserMapper;
import com.oa.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author syb123
 * @since 2019-01-22
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements IOrganizationService {

    private final OrganizationMapper organizationMapper;
    private final UserMapper userMapper;

    @Autowired
    public OrganizationServiceImpl(OrganizationMapper organizationMapper,  UserMapper userMapper) {
        this.organizationMapper = organizationMapper;
        this.userMapper = userMapper;

    }

    @Override
    @CommonService
    public PageResult<Organization> findList(Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            List<Organization> list = organizationMapper.findList();
            return new PageResult<>(list);
        } else {
            // 当前页，总条数 构造 page 对象
            Page<Organization> page = new Page<>(pageNum, pageSize);
            //查询
            List<Organization> list = organizationMapper.findList(page);
            return new PageResult<>(list);
        }
    }

    /**
     * 根据id查询
     */
    @Override
    @CommonService
    public Organization findOrganizationById(String id) {
        return organizationMapper.findById(id);
    }

    /**
     * 添加组织架构
     *
     * @param organizationDTO
     * @return
     */
    @Override
    @CommonService
    public Resp addOrganization(OrganizationDTO organizationDTO) throws BusinessException {

        Organization organization = new Organization();

        BeanUtils.copyProperties(organizationDTO, organization);

        organization.setCreateTime(new Date());
        organization.setSort(sortNumMax());

        try {
            insert(organization);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("添加组织结构失败!");
        }

        return new Resp<String>().success("添加组织结构成功!");
    }

    /**
     * 新增组织结构-公司
     *
     * @param companyDTO
     * @return
     */
    @Override
    @CommonService
    public Resp addCompany(CompanyDTO companyDTO) throws BusinessException {

        Organization organization = new Organization();

        BeanUtils.copyProperties(companyDTO, organization);

        organization.setPId(Constant.IS_COMPANY);
        organization.setCreateTime(new Date());
        organization.setSort(sortNumMax());

        try {
            insert(organization);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("添加公司失败!");
        }
        return new Resp<String>().success("添加公司成功!");
    }

    /**
     * 根据组织架构主键id查询组织架构详情
     *
     * @param id
     * @return
     */
    @Override
    @CommonService
    public Resp findOrganizationDetailsById(String id) throws DataIsEmptyException {
        OrganizationDetailsVO organizationDetailsVO = organizationMapper.findOrganizationDetailsById(id);
        return new Resp<OrganizationDetailsVO>().success(organizationDetailsVO);
    }

    /**
     * 修改组织结构
     *
     * @param
     * @return
     */
    @Override
    public Resp updateOrganization(OrganizationUpdateDTO organizationUpdateDTO) throws BusinessException {
        Organization organization = new Organization();
        BeanUtils.copyProperties(organizationUpdateDTO, organization);
        try {
            updateById(organization);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("修改组织架构失败!");
        }
        return new Resp<String>().success("修改组织架构成功!");
    }

    /**
     * 根据组织架构主键id删除组织架构
     *
     * @param id
     * @return
     */
    @Override
    @CommonService
    public Resp deleteOrganization(String id) throws DataIsEmptyException, BusinessException {

        Organization organization = findOrganizationById(id);

        //判断是否存在下级组织
        List<Organization> organizationAll = organizationMapper.selectList(new EntityWrapper<Organization>().eq("is_deleted", Constant.IS_DELETE_NO));
        int count = 0;
        for (Organization o : organizationAll) {
            if (organization.getId().equals(o.getPId())) {
                count++;
                break;
            }
        }
        if (count > 0) {
            throw new BusinessException("该组织架构还存在下级组织,无法删除!");
        }

        //判断是否存在员工
        List<User> userList = userMapper.selectList(new EntityWrapper<User>().eq("is_deleted", Constant.IS_DELETE_NO));
        if (CollUtil.isNotEmpty(userList)) {
            int countUser = 0;
            for (User user : userList) {
                if (user.getCompanyId().equals(organization.getId()) || user.getDepartmentId().equals(organization.getId())) {
                    countUser++;
                    break;
                }
            }
            if (countUser > 0) {
                throw new BusinessException("该组织架构还存在员工,无法删除!");
            }
        }

        try {
            organization.setIsDeleted(Constant.IS_DELETE_YES);
            updateById(organization);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("删除组织架构失败!");
        }

        return new Resp<String>().success("删除组织架构成功!");
    }

    /**
     * 根据组织架构id查询该部门所属的公司id
     *
     * @param departmentId 部门id
     * @return
     */
    @Override
    public String findCompanyIdByDepartmentId(String departmentId) {

        Organization organization = selectById(departmentId);

        if ("0".equals(organization.getPId())) {
            return organization.getId();
        }

        return findTopOrganization(organization.getPId());
    }

    @Override
    public List<OrganizationTreeVO> findOrganizationTree(String organizationName, String pId) {

        Wrapper wrapper = new EntityWrapper<Organization>().eq("is_deleted", 2);

        List<Organization> organizations = null;

        if (StringUtils.isNotEmpty(organizationName)) {
            wrapper.like("organization_name", organizationName);
            organizations = organizationMapper.selectList(wrapper);
        } else {
            organizations = organizationMapper.findList();
            return recursionOrganization(getOrganizationsTreeList(organizations), pId);
        }
        return getOrganizationsTreeList(organizations);
    }

    public List<OrganizationTreeVO> getOrganizationsTreeList(List<Organization> organizations){
        List<OrganizationTreeVO> organizationTreeVOList = new ArrayList<>();
        organizations.forEach(d -> {
            OrganizationTreeVO organizationTreeVO = new OrganizationTreeVO();
            organizationTreeVO.setId(d.getId());
            organizationTreeVO.setOrganizationName(d.getOrganizationName());
            organizationTreeVO.setPId(d.getPId());
            organizationTreeVO.setSort(d.getSort());
            organizationTreeVO.setRemake(d.getRemake());
            organizationTreeVO.setCreateTime(d.getCreateTime());
            organizationTreeVOList.add(organizationTreeVO);
        });
        return organizationTreeVOList;
    }

    @Override
    public List<OrganizationTreeVO> findOrganizationUserTree() {
        return recursionOrganization(organizationMapper.findOrganizationUserTree(), "0");
    }

    public List<OrganizationTreeVO> recursionOrganization(List<OrganizationTreeVO> list, String pid){
        // 查找所有菜单
        List<OrganizationTreeVO> childrenList = new ArrayList<>();
        list.stream().filter(d -> Objects.equals(pid, d.getPId()))
                .collect(Collectors.toList())
                .forEach(d -> {
//                    if(d.getPId().equals("0"))
//                        d.setPermissionVOList(recursionPermission(list, d.getId()));
                    d.setOrganizationTreeVOList(recursionOrganization(list, d.getId()));
                    childrenList.add(d);
                });
        return childrenList;
    }

    /**
     * 查询顶级的组织架构
     *
     * @param pId
     * @param
     * @return
     */
    public String findTopOrganization(String pId) {

        Organization organization = organizationMapper.findTopOrganization(pId);

        if ("0".equals(organization.getPId())) {
            return organization.getId();
        }

        return findTopOrganization(organization.getPId());


    }

    /**
     * 获取组织架构的的最大排序值
     *
     * @return
     */
    public Integer sortNumMax() {

        List<Integer> sortList = new ArrayList<>();

        List<Organization> organizationAll = organizationMapper.selectList(new EntityWrapper<Organization>().eq("is_deleted", Constant.IS_DELETE_NO));
        if (CollUtil.isNotEmpty(organizationAll)) {
            organizationAll.forEach(x -> {
                sortList.add(x.getSort());
            });

            Integer max = Collections.max(sortList);
            return max + Constant.DEFAULT_SORT;
        }

        return Constant.DEFAULT_SORT;
    }

}
